<!--
 * @Author: Penk
 * @LastEditors: Penk
 * @LastEditTime: 2023-09-23 15:27:15
 * @FilePath: \web-interview-questions\遍历.html
 * @email: 492934056@qq.com
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
</head>

<body>
  <script>
    let arr = [111, 222, 333, 444];
    let obj = { a: 'aaa', b: 'bbb' };

    console.log('===============遍历的方式==============');
    // 数组
    // for in 遍历的是下标
    console.log("for in 打印数组：");
    for (let i in arr) {
      console.log(arr[i]);
    }
    console.log("for of 打印数组：");
    // for of 遍历的是键值
    for (let i of arr) {
      console.log(i);
    }
    console.log("for循环 打印数组：");
    // for循环
    for (let i = 0; i < arr.length; i++) {
      console.log(arr[i]);
    }
    console.log("forEach 打印数组：");
    // forEach
    arr.forEach(item => {
      console.log(item);
    })

    console.log('===============遍历的对象的差异==============');
    // 对象
    // for in 遍历的是键名
    console.log("for in 打印对象：");
    for (let i in obj) {
      console.log(obj[i]);
    }

    try {
      // for of 不能遍历普通对象，除了有迭代器iterator 比如map，set，weakMap 等
      for (let i of obj) {
        console.log(i);
      }
    } catch (error) {
      console.error("for of 不能遍历普通对象：", error.message);
    }

    console.error("for循环 打印对象：~~~无效...");

    try {
      obj.forEach(item => {
        console.log(item);
      })
    } catch (error) {
      console.error("forEach 不能遍历普通对象：", error.message);
    }


  </script>
</body>

</html>